package org.dromara.rank.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.dromara.rank.domain.entity.RankItem;
import org.dromara.rank.domain.entity.RankProfile;
import org.dromara.rank.domain.vo.UserRankVO;
import org.dromara.rank.mapper.RankItemMapper;
import org.dromara.rank.mapper.RankProfileMapper;
import org.dromara.rank.service.IUserRankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.stream.Stream;

@Service
public class UserRankServiceImpl implements IUserRankService {

    @Autowired
    private RankProfileMapper rankProfileMapper;

    @Autowired
    private RankItemMapper rankItemMapper;

    @Override
    public IPage<UserRankVO> getRankPage(Integer pageNum, Integer pageSize){
        if (pageNum == null || pageNum < 1) pageNum = 1;
        if (pageSize == null || pageSize < 1) pageSize = 10;
        if(pageSize>50){
            pageSize=50;
        }
        Page<UserRankVO> page = new Page<>(pageNum, pageSize);
        return rankProfileMapper.selectRankPage(page);
    }

    @Override
    public UserRankVO getUserRankDetail(Long userId) {
        UserRankVO detail = rankProfileMapper.selectUserRankDetail(userId);
        if(ObjectUtil.isNull( detail)){
            throw new RuntimeException("用户为参与排名或者数据不存在");
        }
        return detail;
    }

    @Override
    public void addScoreToUser(Long userId,String itemCode,String profile){
        //获取积分项
        RankItem item = rankItemMapper.selectOne(new LambdaQueryWrapper<RankItem>().eq(RankItem::getItemName, itemCode));
        if(item ==null){
            throw new RuntimeException("积分项不存在"+itemCode);
        }

        Integer score = item.getItemScore();
        String type = item.getType();

        RankProfile file = rankProfileMapper.selectOne(
            new LambdaQueryWrapper<RankProfile>()
                .eq(RankProfile::getSysUserId, userId)
        );

        if (file == null) {
            // 首次加分，创建新档案
            file = new RankProfile();
            file.setSysUserId(userId);
            file.setProfile("");
            file.setDevScore(0);
            file.setCompetitionScore(0);
            file.setBugScore(0);
            file.setHwScore(0);
            file.setTotalScore(0);
        }

        switch (type.toLowerCase()){
            case "dev":
                file.setDevScore((getOrZero(file.getDevScore())+ score));
                break;
            case "competition":
                file.setCompetitionScore((getOrZero(file.getCompetitionScore())+ score));
                break;

            case "bug":
                file.setBugScore((getOrZero(file.getBugScore())+ score));
                break;

            case "hw":
                file.setHwScore((getOrZero(file.getHwScore())+ score));
                break;

            default:
                throw new RuntimeException("积分项类型错误"+type);
        }

        Integer totalScore = Stream.of(file.getDevScore(), file.getCompetitionScore(),
            file.getHwScore(), file.getBugScore())// 1. 创建包含4个积分的流
            .filter(Objects::nonNull)// 2. 过滤掉null值
            .mapToInt(Integer::intValue)// 3. 转换为int
            .sum();
        file.setTotalScore(totalScore);
        file.setUpdateTime(new java.util.Date());
        String currentProfile = file.getProfile();
        if(currentProfile!=null){
            file.setProfile(currentProfile+","+profile);
        }else {
            file.setProfile(profile);
        }

        if(file.getId()==null){
            rankProfileMapper.insert(file);
        }else{
            rankProfileMapper.updateById(file);
        }




    }

    private Integer getOrZero(Integer value) {
        return value == null ? 0 : value;
    }

}
